package com.wang.example.bio;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.Socket;

public class BioSeverHandler implements Runnable{
    private Socket socket;
    public BioSeverHandler(Socket socket){
        this.socket = socket;
    }
    @Override
    public void run() {
        try (
                // 获取客户端输入流
                InputStream is = socket.getInputStream();
                //打印输出流
                PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
        ) {
            byte[] b = new byte[1024];
            while (true) {//循环读取数据
                //read()阻塞，只有等到数据准备好，才会往下执行
                int data = is.read(b);
                if (data != -1) {
                    String info = new String(b, 0, data, "GBK");
                    System.out.println(info);
                    //告诉客户端，收到了消息
                    pw.println("收到消息：" + info);
                } else {
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
